package com.liqi.frame.comm.controller;

import cn.hutool.core.util.StrUtil;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.exception.GlobalException;
import com.liqi.frame.comm.properties.AppProperties;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.token.UserToken;
import com.liqi.frame.comm.util.JwtUtils;
import com.liqi.frame.comm.util.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liqi on 2017/8/3.
 */
@Controller
@RequestMapping({"/ajax","/api"})
@Slf4j
public class LoginAjaxController {
//    private static final Log log = LogFactory.get();

    //    @Value("${main.indexPage}")
//    private String mainIndexPage;
    @Autowired
    private AppProperties appProperties;

    @RequestMapping({"login"})
    @ResponseBody
    public HttpResult login(@RequestBody Map params,
                            HttpServletRequest request) {
        String username = params.get("username")+"";
        String pswd = params.get("pswd")+"";

        UserToken token = new UserToken(username, pswd);
        Subject subject = ShiroUtil.getSubject();
        try {
            subject.login(token);
            SavedRequest savedRequest = WebUtils.getSavedRequest(request);
            String url = "";

            if (savedRequest == null) {
                url = appProperties.getIndexPage();
            } else {
                String urlRemovePrefix = StrUtil.removePrefix(savedRequest.getRequestUrl(), request.getContextPath());
                if (savedRequest.getRequestUrl() == null ||
                        savedRequest.getRequestUrl().equalsIgnoreCase(Constants.LOGIN_AJAX_URL) ||
                        "".equals(urlRemovePrefix) ||
                        "/".equals(urlRemovePrefix)) {
                    url = appProperties.getIndexPage();
                } else {
                    // 跳转到登录前的页面
                    url = urlRemovePrefix;
                }
            }
            Map data = new HashMap();
            data.put("url", url);
            data.put("jwtToken", JwtUtils.newToken(username, pswd));

            request.setCharacterEncoding("utf-8");  //这里不设置编码会有乱码

            HttpResult result = new HttpResult(ResultEnum.SUCCESS);
            result.setData(data);
            return result;
        } catch (Exception e) {
            throw new GlobalException(ResultEnum.USERNAME_PASSWORD_INCORRECT);
//            HttpResult result = new HttpResult(false, "用户名或密码错误！");
//            data.addAttribute(result);
//            return result;
        }

    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping({"logout"})
    @ResponseBody
    public HttpResult logout() {
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        try {
//            log.info("=================");
//            HttpUtil.post("http://127.0.0.1:8060/logout_demo", "");
            TokenUtil.logout();
        } catch (Exception e) {
            result.setCode(ResultEnum.FAILURE.getCode());
            result.setMsg("退出出错!");
            log.error("退出出现错误，{}", e.getMessage());
        }
        return result;
    }

}
